<template>
  <IFexHeaderMain>
    <template #header>
      <IHeader :showBankVail="false">首页</IHeader>
    </template>
    <view class="page-container whov">
      <view class="flex_left_right">
        <view class="subtitle flex_right">
          <view class="icon_font t-icon-jiaotongdingweilvyou_yidingwei_local"></view>
          <text style="margin-left: 5px">{{ accountInfo.pointName }} ({{ accountInfo.counterAlias }})</text>
        </view>
        <view class="flex_left" style="color: #3b82f6; line-height: 44rpx"> 24小时营业</view>
      </view>

      <view class="tip_content">
        <view class="tip_title flex_left_right">
          <view class="flex_right">如何取件？</view>
          <view class="flex_left">(免费寄存)</view>
        </view>
        <view class="tip_text">在屏幕上用【手机号码+4位数密码】进行取件。</view>
      </view>

      <view class="form-group">
        <view class="form_label">获取手机号</view>
        <uni-easyinput class="input-field" placeholder-style="font-size:48rpx;" :disabled="true" prefixIcon="phone-filled" :maxlength="11" v-model="form.phone" placeholder="手机号">
          <template #right>
            <button class="phone-btn" open-type="getPhoneNumber" v-if="userInfo && userInfo.userId && !form.phone" @getphonenumber="getPhoneNumber">获取手机号</button>
          </template>
        </uni-easyinput>
      </view>
      <view class="form-group">
        <view class="form_label">输入4位存包密码</view>
        <uni-easyinput
          class="input-field"
          placeholder-style="font-size:48rpx;"
          prefixIcon="locked-filled"
          v-model="form.password"
          type="password"
          :maxlength="4"
          placeholder="请输入4位存包密码"
          :clearable="false"
        ></uni-easyinput>
      </view>
      <button form-type="submit" class="next-btn" @click="nextFun"> 下一步 </button>
      <!-- <button form-type="submit" class="next-btn" @click="goGLFun"> 管理端 </button> 
      <button form-type="submit" class="next-btn" @click="gotzrGLFun"> 投资人 </button>  -->
    </view>
    <template #footer><ITabBar :index="0" /></template>
    <view class="mobile_mark wrapper" v-if="isShow">
      <view class="mark_content">
        <view class="mark_title"> 确认手机号码及取包密码： </view>
        <view class="mark_label">取包手机号码</view>
        <view class="mark_value">{{ form.phone }}</view>
        <view class="mark_label">取包密码：</view>
        <view class="mark_value">{{ form.password }}</view>
        <view class="flex_left_right mark_btn" style="margin: 40rpx 0 20rpx 0">
          <button form-type="submit" class="next-btn mark_btn_oper oper_back" @click="isShow = false"> 返回修改 </button>
          <button form-type="submit" class="next-btn mark_btn_oper" style="margin-left: 10rpx" @click="nextSubmitFun"> 正确 </button>
        </view>
      </view>
    </view>
  </IFexHeaderMain>
</template>

<script setup lang="ts" name="index">
  import { computed, ref, watch } from 'vue'
  import ITabBar from '@/components/container/ITabBar.vue'
  import IFexHeaderMain from '@/components/container/IFexHeaderMain.vue'
  import IHeader from '@/components/container/IHeader.vue'
  import { getDeviceCabinetInfo, reservationOrder } from '@/api/index'
  import useToastMsg from '@/hooks/sysMsg'
  import { useNavigatePage } from '@/hooks/navigateTo'
  import useAccountStore from '@/store/account'
  import useUserInfoStore from '@/store/userInfo'
  import { LoginStatusCheck } from '@/utils/login'
  import { getLoginRes, getUserPhoneNumber, selectUserInfo, userLogin } from '@/api/login'
  import { onLoad } from '@dcloudio/uni-app'
  import { subscribeMsg } from '@/utils'
import { getWxappId } from '@/utils/platform'
  const isClickable = ref(true)
  const toastMsg = useToastMsg()
  const accountStore = useAccountStore()
  const userInfoStore = useUserInfoStore()
  const navigatePage = useNavigatePage()
  userInfoStore.setPlatformType('khd')
  const userInfo = computed(() => userInfoStore.getUserInfo)
  const accountInfo = computed(() => accountStore.getAccountDetails)
  const isProjectVail = ref(false)
  const isShow = ref(false)
  const form = ref({
    phone: '',
    password: '',
  })
  const nextFun = async () => {
    // 新增：如果不可点击则直接返回
    if (!isClickable.value) return
    if (!form.value.phone || !form.value.password) {
      toastMsg.showToast('手机号和密码不能为空')
      return
    }
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(form.value.phone)) {
      toastMsg.showToast('请输入正确的手机号')
      return
    }
    if (form.value.password.length < 4) {
      toastMsg.showToast('请输入4位密码')
      return
    }
    isShow.value = true
  }
  const nextSubmitFun = () => {
    // 新增：点击后立即禁用按钮
    isClickable.value = false
    LoginStatusCheck(
      async () => {
        try {
          const result = await reservationOrder(accountInfo.value.deviceId, form.value.phone, form.value.password, userInfo.value.userId)
          if (result) {
            if (result.data.doorNo && result.data.userStorageId) {
              navigatePage.navigateTo(
                `/pages/confirmRoom/index?cabinetNo=${result.data.cabinetNo || ''}&doorNo=${result.data.doorNo || ''}&userStorageId=${result.data.userStorageId || ''}&code=${result.data.code || ''}`,
              )
            } else if (result.data.code == 1) {
              toastMsg.showToast(result.data.message)
            } else {
              toastMsg.showToast('没有空余的柜子了')
            }
          }
        } finally {
          setTimeout(() => {
            isShow.value = false
            isClickable.value = true
          }, 1000)
        }
      },
      () => (isClickable.value = true),
    )
  }
  const getUserInfo = async () => {
    const result: any = await selectUserInfo(uni.getStorageSync('deviceId'))
    if (result && result.data.userInfo) {
      userInfoStore.setUserInfo(result.data.userInfo)
      if (result.data.userInfo.isQb == '1' && isProjectVail.value) {
        navigatePage.redirectTo('/pages/baoguo/index')
      }
    }
  }
  const loginFun = () => {
    navigatePage.navigateTo('/pages/login/index')
  }
  const settingUserInfoFun = () => {
    navigatePage.navigateTo('/pages/userInfo/index')
  }

  onLoad(async (options: any) => {
    isProjectVail.value = false
    handleScanParams(options)
  })

  const getPhoneNumber = async (e: any) => {
    LoginStatusCheck(async () => {
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        const loginRes = await getLoginRes()
        if (loginRes.errMsg === 'login:ok') {
          await getUserPhoneNumber(e, loginRes)
          getUserInfo()
        } else {
          toastMsg.showToast('请授权手机号以完成登录')
        }
      }
    })
  }
  const handleScanParams = async (options: any) => {
    let deviceId = uni.getStorageSync('deviceId') || '198'
    if (options && options.scene) {
      const scene = decodeURIComponent(options.scene)
      const params: Record<string, string> = {}
      scene.split('&').forEach((pair) => {
        const [key, value] = pair.split('=')
        if (key) params[key] = value
      })
      deviceId = params.deviceId || '198'
      isProjectVail.value = true
    }
    if (options && options.q) {
      const scene = decodeURIComponent(options.q)
      deviceId = getDeviceIdFromUrl(scene) || '198'
      isProjectVail.value = true
    }
    uni.setStorageSync('deviceId', deviceId)
    console.log(`${deviceId} 我是deviceId`)
    const deviceRes = await getDeviceCabinetInfo(deviceId)
    accountStore.accountDetails = {
      pointName: deviceRes?.data?.pointName || '',
      counterAlias: deviceRes?.data?.counterAlias || '',
      deviceId,
      wxapp_id: getWxappId(),
      wdId: deviceRes?.data?.pointId || '',
    }

    if (!uni.getStorageSync('token')) {
      const loginRes = await getLoginRes()
      if (loginRes.errMsg === 'login:ok') {
        const result: any = await userLogin(loginRes)
        if (result) {
          uni.setStorageSync('token', result.data.token)
          uni.setStorageSync('rtoken', result.data.token)
        }
      }
    }
    getUserInfo()
  }
  function getDeviceIdFromUrl(url: string): string | null {
    const match = url.match(/[?&]deviceId=([^&]+)/)
    return match ? match[1] : null
  }
  const goGLFun = () => {
    navigatePage.redirectTo('/pages/zmanager/index/index')
  }
  const gotzrGLFun = () => {
    navigatePage.redirectTo('/pages/invest/index/index')
  }
  watch(
    userInfo,
    (val: any) => {
      if (val && val.phoneNumber) {
        form.value.phone = val.phoneNumber
      }
    },
    { immediate: true },
  )
</script>

<style scoped lang="scss">
  .page-container {
    background: #ffffff;
    padding: 30rpx;
  }
  .mark_btn {
    padding: 0 60rpx;
    .mark_btn_oper {
      font-weight: 600;
    }
    .oper_back {
      margin-right: 10rpx;
      background-color: #fff;
      color: #377df6;
      border: 2px solid #377df6;
    }
  }
  .mark_content {
    border-radius: 12rpx;
    background: #fff;
  }
  .mark_label {
    padding: 40rpx 60rpx;
    font-size: 36rpx;
  }
  .mark_value {
    text-align: center;
    font-size: 66rpx;
    color: #373737;
  }
  .mark_title {
    border-bottom: 1px solid #eee;
    padding: 40rpx 60rpx;
    font-size: 48rpx;
  }
  .mobile_mark {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
  }
  .form_label {
    font-size: 32rpx;
    margin-bottom: 20rpx;
    color: #585858;
    font-weight: 600;
  }
  .tip_content {
    margin: 40rpx 0;
    background: linear-gradient(to right, #fe6c19, #ff9a32);
    color: #fff;
    padding: 30px 20px;
    border-radius: 5px;
    padding: 30rpx;
    .tip_title {
      font-weight: 700;
      font-size: 40rpx;
      margin-bottom: 30rpx;
    }
    .tip_text {
      font-size: 28rpx;
    }
  }

  .subtitle {
    font-size: 34rpx;
    font-weight: 500;
  }

  .form-group {
    position: relative;
    margin-bottom: 40rpx;
  }

  // .input-field {
  //   width: 100%;
  //   border-radius: 15rpx;
  //   font-size: 66rpx;
  //   transition: all 0.3s;
  //   box-sizing: border-box;
  // }
  /* 登录按钮 */
  .next-btn {
    width: 100%;
    background-color: #377df6;
    color: white;
    border: none;
    border-radius: 15rpx;
    font-size: 34rpx;
    font-weight: 500;
    transition: all 0.3s;
    margin-bottom: 30rpx;
  }
  :deep(.uni-easyinput) {
    padding: 0;
  }
  .icon_font {
    display: inline-block;
    width: 1.3em;
    height: 1.3em;
    fill: currentColor;
    vertical-align: bottom;
  }
  // /* 统一内部 input 高度 */
  :deep(.uni-easyinput__content-input) {
    height: 98rpx !important;
    line-height: 98rpx !important;
    font-size: 60rpx !important;
    box-sizing: border-box;
    padding: 0 20rpx;
    display: flex;
    align-items: center;
  }
  :deep(.uni-icons) {
    font-size: 60rpx !important;
  }
  :deep(.uniui-phone-filled) {
    color: #377df6 !important;
  }
  :deep(.uniui-locked-filled) {
    color: #377df6 !important;
  }

  .phone-btn {
    height: 98rpx !important;
    line-height: 98rpx !important;
    font-size: 28rpx;
    background-color: #3b82f6;
    border-color: #3b82f6;
    color: #ffffff;
    padding: 0 10px;
  }
</style>
